<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;

use App\Models\Issue;

class FetchIssues extends Command
{
    const START = 1980;
    const LINK = 'http://www.zoores.ac.cn/EN/article/showTenYearVolumnDetail.do?nian=';

    const JOURNAL_ID = 1;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:issue {year?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'get all issue from zoores.ac.cn';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $year = $this->argument('year');
        
        if ($year) {
            $this->getIssuesByYear($year);
        } else {
            foreach (range(1980, 2018) as $year) {
                $this->getIssuesByYear($year);
            }
        }

        $this->info('.................Done.');
    }

    public function getIssuesByYear($year)
    {
        $url = self::LINK . $year;

        try {
            $client = new Client();
            $guzzleClient = new GuzzleClient(array(
                'timeout' => 60,
            ));
            $client->setClient($guzzleClient);
            $crawler = $client->request('GET', $url);

            $issueItems = $crawler->filter('table')->eq(3)->filterXPath('//a[@class="J_WenZhang"]');
            $issuesArr = [];
            $issueItems->each(function($item, $i) use (&$issuesArr) {
                $uri = $item->link()->getUri();
                $zrId = 0;
                if (preg_match('/_(\d+)\.shtml$/i', $uri, $match)) {
                    $zrId = $match[1];
                }

                $nbsp = html_entity_decode("&nbsp;");
                $item = html_entity_decode($item->text());
                $info = trim(preg_replace('/\s+/is', ' ', str_replace('&nbsp;', ' ', str_replace($nbsp, ' ', $item))));

                $issueArr = explode(' ', $info);

                $no = trim(str_replace('No.', '', $issueArr[2]));
                $page = explode('-', substr($issueArr[3], 3));
                $issuesArr[$no] = [
                    'journal_id' => self::JOURNAL_ID,
                    'title' => $info,
                    'title_en' => $info,
                    'year' => trim($issueArr[0]),
                    'volume' => trim(str_replace('Vol.', '', $issueArr[1])),
                    'issue' => $no,
                    'page_start' => $page[0],
                    'page_end' => $page[1],
                    'journal_created' => $issueArr[4],
                    'journal_published' => $issueArr[4],
                    'zr_id' => $zrId
                ];
            });
            ksort($issuesArr);

            foreach ($issuesArr as $issue) {
                Issue::updateOrCreate(['zr_id' => $issue['zr_id']], $issue);
                $this->line('Update a issue:  ' . $issue['title']);
            }

            sleep(1);


        } catch (\Exception $e) {
            print_r($e->getMessage());
            echo 'error occurred';
            exit;
        }

    }

}
